package com.excalibur.core.util.web;

import java.io.BufferedReader;
import java.io.IOException;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public final class WebUtils {

	private final static Logger logger = LoggerFactory.getLogger(WebUtils.class);

	/**
	 * 去请求体字符串
	 * 
	 * @param request
	 * @return
	 */
	public static String getRequestBody(HttpServletRequest request) {
		StringBuilder sb = new StringBuilder();
		try {
			BufferedReader reader = request.getReader();
			String line = null;
			while ((line = reader.readLine()) != null) {
				sb.append(line);
			}
		} catch (IOException e) {
			logger.warn("IOException: ", e);
		}
		return sb.toString();
	}

	/**
	 * 获取X-Forwarded-For第一个ip
	 * @param request
	 * @return String, ip address
	 */
	public static String getIpAddress(HttpServletRequest request) {
		String ip = parseIpFromRequest(request);
		if (StringUtils.isNotBlank(ip) && StringUtils.indexOf(ip, ",") > 0) {
			String[] ipArray = StringUtils.split(ip, ",");
			for (String ipItem : ipArray) {
				if (!ipItem.equalsIgnoreCase("unknown")) {
					ip = ipItem;
					break;
				}
			}
		}
		if (StringUtils.isBlank(ip)) {
			ip = "127.0.0.1";
			logger.info("ipaddress is blank, set default value : " + request.getRequestURI());
		}
		return ip;
	}
	
	/**
	 * 获取X-Forwarded-For最后的ip
	 * @param request
	 * @return
	 */
	public static String getLastIpAddress(HttpServletRequest request){
		return getLastIpAddressExcludeWhite(request, null);
	}
	
	/**
	 * 获取X-Forwarded-For最后的ip，排除白名单
	 * @param request
	 * @param whites
	 * @return
	 */
	public static String getLastIpAddressExcludeWhite(HttpServletRequest request, Set<String> whites){
		String ip = parseIpFromRequest(request);
		if (StringUtils.isNotBlank(ip) && StringUtils.indexOf(ip, ",") > 0) {
			String[] ipArray = StringUtils.split(ip, ",");
			if(ipArray != null){
				int len = ipArray.length;
				for(int i=len-1; i>=0; i--){
					ip = ipArray[i].trim();
					if(whites == null){
						break;
					} else if(!whites.contains(ip)){
						break;
					}
				}
			}
		}
		if (StringUtils.isBlank(ip) || ip.equalsIgnoreCase("unknown")) {
			ip = "127.0.0.1";
			logger.info("ipaddress is blank, set default value : " + request.getRequestURI());
		}
		return ip;
	}

	/**
	 * 取得ip串
	 * @param request
	 * @return
	 */
	public static String getAllIpAddress(HttpServletRequest request) {
		return parseIpFromRequest(request);
	}

	/**
	 * 从request取得ip串
	 * @param request
	 * @return
	 */
	private static String parseIpFromRequest(HttpServletRequest request) {
		String ip = request.getHeader("X-Forwarded-For");
		if (StringUtils.isBlank(ip) || StringUtils.equalsIgnoreCase(ip, "unknown")) {
			ip = request.getHeader("Proxy-Client-IP");
		}
		if (StringUtils.isBlank(ip) || StringUtils.equalsIgnoreCase(ip, "unknown")) {
			ip = request.getHeader("WL-Proxy-Client-IP");
		}
		if (StringUtils.isBlank(ip) || StringUtils.equalsIgnoreCase(ip, "unknown")) {
			ip = request.getHeader("HTTP_CLIENT_IP");
		}
		if (StringUtils.isBlank(ip) || StringUtils.equalsIgnoreCase(ip, "unknown")) {
			ip = request.getHeader("HTTP_X_FORWARDED_FOR");
		}
		if (StringUtils.isBlank(ip) || StringUtils.equalsIgnoreCase(ip, "unknown")) {
			ip = request.getRemoteAddr();
		}
		return ip;
	}

	public static String combinePrefixAndKey(String prefix, String key) {
		return prefix + key;
	}
	
}
